// components/home-chat/home-chat.ts
import api from "../../api/index";
import common from "../../common/index";

Component({

  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    uid: '',
    questionStr: '',
    conditionStatus: {
      r1: 1,
      aispire: 0,
      knowledge: 0,
      network: 0,
    },
    inspectionList: [],
    currentTemplateData: null as any,
    autoFocus: false,
    selectionStart: -1,
    selectionEnd: -1,
    shouldAutoCallPaperInfo: false,
    lastQuestionStr: '', // 用于检测输入变化
    templatePlaceholderPosition: -1, // 模板占位符位置
    keepCursorTimer: null as any, // 保持光标的定时器
    originalTemplateText: '', // 保存原始模板文本
    uploadedFiles: [] as Array<any>, // 已上传的文件列表
    fileIconMap: {
      pdf: '../../assets/image/pdf-icon.png',
      doc: '../../assets/image/word-icon.png',
      docx: '../../assets/image/word-icon.png',
      ppt: '../../assets/image/ppt-icon.png',
      pptx: '../../assets/image/ppt-icon.png',
      txt: '../../assets/image/txt-icon.png',
      md: '../../assets/image/txt-icon.png',
      markdown: '../../assets/image/txt-icon.png',
      xls: '../../assets/image/excel-icon.png',
      xlsx: '../../assets/image/excel-icon.png',
      csv: '../../assets/image/excel-icon.png',
      default: '../../assets/image/def-icon.png'
    }
  },
  lifetimes: {
    attached() {
      // const user = common.getAppUserInfo()
      // this.data.uid = user.uid
      // this.setData({
      //   uid: user.uid,
      // })
      // if (this.data.uid) {
      //   this.getInspectionList()
      // }
    },
    detached() {
      // 组件销毁时清除定时器
      if (this.data.keepCursorTimer) {
        clearInterval(this.data.keepCursorTimer)
        this.data.keepCursorTimer = null
      }
    }
  },
  pageLifetimes: {
    show() {
      const user = common.getAppUserInfo()
      this.data.uid = user.uid
      this.setData({
        uid: user.uid,
      })
      this.getInspectionList()
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    changeConditionStatus(e: BaseEvent){
      const k: 'r1' | 'aispire' | 'knowledge' | 'network' = e.currentTarget.dataset.code
      if(this.data.conditionStatus[k]) {
        this.data.conditionStatus[k] = 0
      } else {
        this.data.conditionStatus[k] = 1
      }
      this.setData({
        [`conditionStatus.${k}`]: this.data.conditionStatus[k]
      })
    },
    sendQuestion(){
      if (!this.data.questionStr && (!this.data.uploadedFiles || this.data.uploadedFiles.length === 0)) {
        return
      }
      if (!this.data.uid) {
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        })
        return
      }
      const uploadedFilePaths = (this.data.uploadedFiles || [])
        .map((file: any) => file.path)
        .filter((path: string) => !!path)
      this.triggerEvent('startChat', {
        condition: this.data.conditionStatus,
        text: this.data.questionStr,
        files: uploadedFilePaths
      })
    },
    /**
     * 获取10个推荐的灵感
     */
    async getInspectionList() {
      this.data.inspectionList = []
      try {
        const res: any = await api.inspirationRecommend({
          uid: this.data.uid,
          page_index: 1,
          page_size: 10,
        })
        if (res.data && res.data.length) {
          res.data.forEach((item: any) => {
            item.image_url = 'https://www.aispire.info' + item.image_url.replace(/.*?(?=\/inspiration_images)/, '').replace(/.*?(?=\/private_knowledge)/, '')
            item.icon = item.icon.replace(/.*?(?=\/user_portrait)/, '')
          })
          this.data.inspectionList = res.data
        }
      } catch(e){
        console.log(e)
      }
      this.setData({
        inspectionList: this.data.inspectionList
      })
    },
    handleGotoInspectionPage(){
      this.triggerEvent('toInsPage')
    },
    handleGotoInspectionDetailPage(e: BaseEvent){
      const {item} = e.currentTarget.dataset
      this.triggerEvent('toInsDetlPage', item)
    },
    async handleTemplateQuestion(e: BaseEvent){
      const dataset = e.currentTarget.dataset
      const {type, year, limit} = dataset
      
      // 清除之前的定时器
      if (this.data.keepCursorTimer) {
        clearInterval(this.data.keepCursorTimer)
        this.data.keepCursorTimer = null
      }
      
      let questionText = ''
      let selectionStart = -1
      let selectionEnd = -1
      
      // 根据模板类型生成可编辑的问题模板（自动删除占位符）
      if (type === 'keyword') {
        // 关键词模板：移除占位符，光标定位到引号内
        questionText = `基于""，查找最近${year || 3}年引用数大于${limit || 100}的10个文献。`
        // 光标位置在引号内（"基于"后面，引号中间）
        selectionStart = 3 // "基于"的长度
        selectionEnd = 3
      } else if (type === 'title') {
        // 标题模板：移除占位符，保留"基于标题"关键词以便chat组件识别
        questionText = '基于标题 ""，查找文献'
        // 光标位置在引号内（两个引号之间）
        // "基于标题 " = 5个字符（索引0-4），索引5是第一个引号，索引6是第二个引号
        // 光标应该在索引6（两个引号之间）
        selectionStart = 6 // 两个引号之间的位置
        selectionEnd = 6
      } else if (type === 'doi') {
        // DOI模板：移除占位符，保留"基于DOI"关键词以便chat组件识别
        questionText = '基于DOI ""，查找文献'
        // 光标位置在引号内（两个引号之间）
        // "基于DOI " = 6个字符（索引0-5），索引6是第一个引号，索引7是第二个引号
        // 光标应该在索引7（两个引号之间）
        selectionStart = 7 // 两个引号之间的位置
        selectionEnd = 7
      }
      
      if (questionText) {
        // 保存模板类型和数据，用于后续处理
        this.data.currentTemplateData = {
          type,
          year,
          limit
        }
        
        // 保存占位符位置和原始模板文本
        this.data.templatePlaceholderPosition = selectionStart
        this.data.originalTemplateText = questionText
        
        // 先设置文本和光标位置
        this.setData({
          questionStr: questionText,
          selectionStart: selectionStart,
          selectionEnd: selectionEnd,
          autoFocus: true
        })
        
        // 延迟一点时间确保textarea已经更新并获得焦点
        setTimeout(() => {
          // 再次设置光标位置，确保定位准确
          this.setData({
            selectionStart: selectionStart,
            selectionEnd: selectionEnd
          })
          
          // 创建定时器，持续更新光标位置，确保光标在占位符位置闪烁
          this.data.keepCursorTimer = setInterval(() => {
            // 只有当文本内容还是模板文本时，才保持光标位置
            if (this.data.questionStr === this.data.originalTemplateText && this.data.templatePlaceholderPosition >= 0) {
              this.setData({
                selectionStart: this.data.templatePlaceholderPosition,
                selectionEnd: this.data.templatePlaceholderPosition
              })
            } else {
              // 文本已经改变，清除定时器
              if (this.data.keepCursorTimer) {
                clearInterval(this.data.keepCursorTimer)
                this.data.keepCursorTimer = null
              }
              this.data.templatePlaceholderPosition = -1
              this.data.originalTemplateText = ''
            }
          }, 100) // 每100ms更新一次光标位置
          
          // 如果是标题或DOI模板，监听输入变化，当用户输入完内容后自动调用接口
          if (type === 'title' || type === 'doi') {
            // 标记需要自动调用接口
            this.data.shouldAutoCallPaperInfo = true
          }
        }, 150)
      }
    },
    handleInputChange(e: any){
      const newValue = e.detail.value
      this.setData({
        questionStr: newValue
      })
      
      // 如果文本已经改变，清除保持光标的定时器
      if (this.data.keepCursorTimer && this.data.templatePlaceholderPosition >= 0) {
        if (newValue !== this.data.originalTemplateText) {
          clearInterval(this.data.keepCursorTimer)
          this.data.keepCursorTimer = null
          this.data.templatePlaceholderPosition = -1
          this.data.originalTemplateText = ''
        }
      }
    },
    handleInputFocus(e: any){
      // 如果存在模板占位符位置，且当前文本还是模板文本，将光标定位到占位符位置
      if (this.data.templatePlaceholderPosition >= 0 && this.data.questionStr === this.data.originalTemplateText) {
        setTimeout(() => {
          this.setData({
            selectionStart: this.data.templatePlaceholderPosition,
            selectionEnd: this.data.templatePlaceholderPosition
          })
        }, 50)
      }
    },
    handleChooseFile() {
      console.log('[home-chat] handleChooseFile 被调用')
      const maxFileCount = 5
      const currentCount = (this.data.uploadedFiles || []).length
      if (currentCount >= maxFileCount) {
        wx.showToast({
          title: '最多上传5个文件',
          icon: 'none'
        })
        return
      }
      const remaining = maxFileCount - currentCount
      console.log('[home-chat] 准备选择文件，剩余数量:', remaining)
      wx.chooseMessageFile({
        count: remaining,
        type: 'file',
        extension: ['pdf', 'doc', 'docx', 'ppt', 'pptx', 'md', 'markdown', 'txt'],
        success: (res) => {
          const tempFiles = res.tempFiles || []
          if (!tempFiles.length) {
            return
          }
          const newFiles = tempFiles.map((file: any) => {
            const extension = this.extractFileExtension(file.name)
            const filePath = file.path || file.tempFilePath || ''
            return {
              name: file.name,
              size: file.size,
              sizeText: this.formatFileSize(file.size),
              path: filePath,
              extension: (extension || 'file').toUpperCase(),
              icon: this.getFileIcon(extension)
            }
          })
          this.setData({
            uploadedFiles: (this.data.uploadedFiles || []).concat(newFiles)
          })
        },
        fail: (err) => {
          console.error('选择文件失败:', err)
          wx.showToast({
            title: '未选择文件',
            icon: 'none'
          })
        }
      })
    },
    handleRemoveFile(e: BaseEvent) {
      const { index } = e.currentTarget.dataset || {}
      const idx = Number(index)
      if (Number.isNaN(idx)) {
        return
      }
      const list = [...(this.data.uploadedFiles || [])]
      list.splice(idx, 1)
      this.setData({
        uploadedFiles: list
      })
    },
    extractFileExtension(filename: string = ''): string {
      const parts = filename.split('.')
      return parts.length > 1 ? (parts.pop() || '').toLowerCase() : ''
    },
    formatFileSize(size: number = 0): string {
      if (!size) {
        return ''
      }
      const kb = size / 1024
      if (kb < 1024) {
        return `${kb.toFixed(1)} KB`
      }
      const mb = kb / 1024
      return `${mb.toFixed(1)} MB`
    },
    getFileIcon(ext: string = ''): string {
      const lower = (ext || '').toLowerCase()
      const map = this.data.fileIconMap || {}
      return map[lower] || map.default || ''
    }
  }
})